package cn.yyx.stockservice.controller;


import cn.yyx.common.R;
import cn.yyx.stockservice.entity.Stock;
import cn.yyx.stockservice.entity.StockQuery;
import cn.yyx.stockservice.service.StockService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.yyx.common.R.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sun
 * @since 2023-10-25
 */
@RestController
@RequestMapping("stock")
@CrossOrigin
public class StockController {
    @Autowired
    private StockService stockService;

    @ApiOperation(value = "查询所有的库存")
    @PostMapping("list/{cp}/{ls}")
    public R select(@PathVariable("cp") Integer cp,@PathVariable("ls") Integer ls,@RequestBody StockQuery stockQuery){
//        List<Stock> list=stockService.list();
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(stockQuery.getTitle())){
            queryWrapper.eq("title",stockQuery.getTitle());
        }
        if (!ObjectUtils.isEmpty(stockQuery.getSupplier())){
            queryWrapper.eq("supplier",stockQuery.getSupplier());
        }
        if (!ObjectUtils.isEmpty(stockQuery.getSupplierPhone())){
            queryWrapper.eq("supplier_phone",stockQuery.getSupplierPhone());
        }
        Page<Stock> page = new Page<>(cp,ls);
        IPage<Stock> stockPage = stockService.page(page, queryWrapper);
        return ok().data("stock",stockPage.getRecords()).data("total",page.getTotal());
      /*return  R.ok().data()*/
    }
    @ApiOperation("添加库存")
    @PostMapping("add")
    public R add(@RequestBody Stock stock){
        return stockService.save(stock)? ok():R.error();
    }
    @ApiOperation("删除库存")
    @DeleteMapping("del/{id}")
    public R delete(@PathVariable String id){
        System.out.println(id);
        return stockService.removeById(id)? ok():R.error();
    }
    @ApiOperation("修改库存")
    @PutMapping("updata")
    public R update(@RequestBody Stock stock){
        return stockService.updateById(stock)?R.ok():R.error();
    }
    @ApiOperation("根据编号查询")
    @GetMapping("get/{id}")
    public R getById(@PathVariable String id) {
        Stock stock = stockService.getById(id);
        return R.ok().data("stock", stock);
    }
}

